package com.lagou.edu.service.impl;


import com.lagou.edu.dao.CodeDao;
import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.service.MailFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

@Service
public class CodeServiceImpl implements CodeService {


    @Autowired
    private MailFeign mailFeign;
    @Autowired
    private CodeDao codeDao;

    @Override
    public boolean createAndSendCode(String email) {
        // 1、生成6位验证码
        String code = generateCode();
        // 2、发送邮件
        mailFeign.sendSimpleMail(email,code);
        // 3、验证码入库
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        long now = System.currentTimeMillis() + 8*60*60*1000; // 格林威治时间+8小时
        lagouAuthCode.setCreateTime(new Date(now));
        long tenMLater = now + 10*60*1000;
        lagouAuthCode.setExpireTime(new Date(tenMLater));
        codeDao.save(lagouAuthCode);
        return true;
    }

    public boolean validateCode(String email, String code){
        Long validate = codeDao.validate(email, code);
        if(validate!= null && validate > 0){
            return true;
        }
        return false;
    }

    //生成6位验证码
    public String generateCode(){
        Random random = new Random();
        String result = "";
        for(int i=0; i<6; i++){
            result += random.nextInt(10);
        }
        return result;
    }
}
